package com.bite.book.controller;

import com.bite.book.constant.Constants;
import com.bite.book.model.Result;
import com.bite.book.model.UserInfo;
import com.bite.book.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", produces = "application/json")
    public Result login(String userName, String password, HttpSession session){
        log.info("用户登录 userName:{}, password: {}", userName, password);
        //1. 参数校验
        //2. 验证用户名和密码
        //3. 存Session
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码不能为空");
        }
        //根据用户名, 查询用户信息, 判断密码是否正确
        UserInfo userInfo = userService.queryUserByName(userName);
        if (userInfo==null || userInfo.getId()<0){
            return Result.fail("用户不存在");
        }
        if (!password.equals(userInfo.getPassword())){
            return Result.fail("账号或密码错误");
        }
        //存储Session
        userInfo.setPassword("");
        session.setAttribute(Constants.USER_SESSION_KEY, userInfo);
        return Result.success("");
    }
}
